import * as echarts from 'echarts'

import React, { useEffect, useRef } from 'react'

import { useAppSelector } from '@/store/hooks'

interface EchartsProps {
  option: echarts.EChartsOption
  style?: React.CSSProperties
}
// type EChartsOption = echarts.EChartsOption

const Echarts: React.FC<EchartsProps> = ({ option, style }) => {
  const chartRef = useRef<HTMLDivElement>(null)
  const chartInstance = useRef<echarts.ECharts | null>(null)
  const { pieData } = useAppSelector((state) => state.echarts)

  useEffect(() => {
    if (chartRef.current) {
      if (!chartInstance.current) {
        chartInstance.current = echarts.init(chartRef.current)
      }

      chartInstance.current?.setOption(option, {
        notMerge: true
      })

      // 监听窗口大小变化
      const resizeObserver = new ResizeObserver(() => {
        chartInstance.current?.resize()
      })
      resizeObserver.observe(chartRef.current)

      return () => {
        resizeObserver.disconnect()
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  useEffect(() => {
    if (chartInstance.current) {
      const chartOption = chartInstance.current.getOption()
      if (chartOption.series && chartOption.series[0].type === 'pie') {
        chartInstance.current?.setOption(
          {
            series: {
              data: pieData
            }
          },
          {
            notMerge: false
          }
        )
      }
    }
  }, [pieData])
  return (
    <>
      <div ref={chartRef} style={style}></div>
    </>
  )
}

export default Echarts
